package me.ingxin.android.permission2.task

import me.ingxin.android.permission2.permissionGranted
import me.ingxin.android.permission2.request.Request
import me.ingxin.android.permission2.request.Task
import me.ingxin.android.permission2.request.TaskChain
import me.ingxin.android.permission2.strategy.ReasonStrategy

/**
 * Created on 2023/7/8 by yin
 * 申请常规权限时的理由弹窗
 */
internal class NormalPermissionsReasonTask : Task {
    override fun runTask(chain: TaskChain, request: Request) {
        if (request.reasonStrategy == ReasonStrategy.Before) {
            showReasonView(chain, request)
        } else {
            chain.proceed(request)
        }
    }

    private fun showReasonView(chain: TaskChain, request: Request) {
        val requestList = ArrayList<String>()
        request.normalPermissions.forEach {
            if (!chain.context.permissionGranted(it)) {
                requestList.add(it)
            }
        }

        if (requestList.isEmpty()) {
            //没有需要申请的常规权限
            chain.proceed(request)
            return
        }

        request.guide.getShowReasonView(chain.context, requestList, {
            it.applyDismiss()
            chain.proceed(request)
        }) {
            it.applyDismiss()
            //用户不同意申请动作，构造一个跳过普通权限申请的request
            chain.proceed(request.newBuilder().skipRequestNormaPermission(true).build())
        }.applyShow()
    }

}